package com.laike.pay.baifuprint;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.telephony.TelephonyManager;

import com.laike.pay.R;
import com.laike.pay.base.MyApplication;
import com.laike.pay.bean.PayOrder;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.TimeUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.pax.gl.imgprocessing.IImgProcessing;
import com.pax.ipp.service.aidl.dal.printer.EFontTypeAscii;
import com.pax.ipp.service.aidl.dal.printer.EFontTypeExtCode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by xlm on 2018/3/13 0013
 */
public class PrinterUtil {

    private static final int FONT_BIG = 28;
    private static final int FONT_NORMAL = 24;
    private static Context mContext;
    private final String TIME_FORMAT = "yyy/MM/dd HH:mm:ss";

    public PrinterUtil(Context context) {
        mContext = context;
    }

    public void printTransaction(final List<PayOrder> order, final String count, final String totalMoney) {
        Bitmap bitmap = generateTransaction(order, count, totalMoney);
        //初始化
        PrinterTester.getInstance().init();
        //字体设置（ASCII，拓展码）
        PrinterTester.getInstance().fontSet(EFontTypeAscii.FONT_8_16, EFontTypeExtCode.FONT_16_16);
        //间距设置（字间距，行间距）
        PrinterTester.getInstance().spaceSet(Byte.parseByte("0"),
                Byte.parseByte("0"));

        //字符打印左边界
        PrinterTester.getInstance().leftIndents(Short.parseShort("0"));
        //打印黑度
        PrinterTester.getInstance().setGray(1);
        String statues = PrinterTester.getInstance().getStatus();
        if (statues.contains("Success")) {
            PrinterTester.getInstance().printBitmap(bitmap);
            PrinterTester.getInstance().start();
        }
    }

    @SuppressLint("MissingPermission")
    public Bitmap generateTransaction(final List<PayOrder> order, String count, String totalMoney) {
        TelephonyManager tm = (TelephonyManager) MyApplication.getContext().getSystemService(Context.TELEPHONY_SERVICE);

        IImgProcessing.IPage page = GetObj.getGL().getImgProcessing().createPage();
        page.adjustLineSpace(3);
        page.addLine().addUnit("交易汇总单", FONT_BIG, IImgProcessing.IPage.EAlign.CENTER, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        Calendar c = Calendar.getInstance();
        String month = ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "";
        String day = c.get(Calendar.DATE) < 10 ? "0" + c.get(Calendar.DATE) : c.get(Calendar.DATE) + "";
        page.addLine().addUnit("开始时间:" + "\t" + c.get(Calendar.YEAR) + "-" + month + "-" + day + " " + "00:00:00", FONT_NORMAL);
        page.addLine().addUnit("结束时间:" + "\t" + c.get(Calendar.YEAR) + "-" + month + "-" + day + " "
                + c.get(Calendar.HOUR_OF_DAY) + ":" + (c.get(Calendar.MINUTE) < 10 ? "0" +
                c.get(Calendar.MINUTE) : c.get(Calendar.MINUTE)) + ":" + (c.get(Calendar.SECOND) < 10 ? "0"
                + c.get(Calendar.SECOND) : c.get(Calendar.SECOND)), FONT_NORMAL);
        page.addLine().addUnit("交易描述:" + "\t" + order.get(0).getBody(), FONT_NORMAL);
        page.addLine().addUnit("终端编号:" + "\t" + SharedPreferencesUtils.getTerminalNumber(), FONT_NORMAL);
        page.addLine().addUnit("设备编号:" + "\t" + String.valueOf(tm.getDeviceId()), FONT_NORMAL);
        page.addLine().addUnit("-------------------------------------------------------", FONT_NORMAL);
        page.addLine().addUnit("收款" + "\t", FONT_BIG, IImgProcessing.IPage.EAlign.CENTER, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        page.addLine().addUnit("笔数:" + "\t" + ((int) Double.parseDouble(count)) + "", FONT_NORMAL);
        page.addLine().addUnit("金额:" + "\t" + totalMoney+"元", FONT_NORMAL);
        page.addLine().addUnit("打印时间:" + "\t" + c.get(Calendar.YEAR) + "-" + month + "-" + day + " " +
                c.get(Calendar.HOUR_OF_DAY) + ":" + (c.get(Calendar.MINUTE) < 10 ? "0" + c.get(Calendar.MINUTE)
                : c.get(Calendar.MINUTE)) + ":" + (c.get(Calendar.SECOND) < 10 ? "0" + c.get(Calendar.SECOND)
                : c.get(Calendar.SECOND)), FONT_NORMAL);
        page.addLine().addUnit("\n\n\n\n", FONT_NORMAL);
        IImgProcessing imgProcessing = GetObj.getGL().getImgProcessing();
        return imgProcessing.pageToBitmap(page, 384);
    }


    public void printDealDetail(final PayOrder order,int index) {
        Bitmap bitmap = generateDealDetail(order,index);
        //初始化
        PrinterTester.getInstance().init();
        //字体设置（ASCII，拓展码）
        PrinterTester.getInstance().fontSet(EFontTypeAscii.FONT_8_16, EFontTypeExtCode.FONT_16_16);
        //间距设置（字间距，行间距）
        PrinterTester.getInstance().spaceSet(Byte.parseByte("0"),
                Byte.parseByte("0"));

        //字符打印左边界
        PrinterTester.getInstance().leftIndents(Short.parseShort("0"));
        //打印黑度
        PrinterTester.getInstance().setGray(1);
        String statues = PrinterTester.getInstance().getStatus();
        if (statues.contains("Success")) {
            PrinterTester.getInstance().printBitmap(bitmap);
            PrinterTester.getInstance().start();
        }
    }

    @SuppressLint("MissingPermission")
    public Bitmap generateDealDetail(final PayOrder order, int index) {
        TelephonyManager tm = (TelephonyManager) MyApplication.getContext().getSystemService(Context.TELEPHONY_SERVICE);

        IImgProcessing.IPage page = GetObj.getGL().getImgProcessing().createPage();
        page.adjustLineSpace(3);
        page.addLine().addUnit("来客特惠", 40, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        page.addLine().addUnit("0799-6870001", FONT_NORMAL);
        page.addLine().addUnit("消费存根", 15, IImgProcessing.IPage.EAlign.RIGHT);
        page.addLine().addUnit("-------------------------------------------------------", FONT_NORMAL);

        page.addLine().addUnit("订单金额:" + "\t" + order.getTotal_amount()+"元", FONT_NORMAL);
        page.addLine().addUnit("消费金额:" + "\t" + order.getPay_amount()+"元", FONT_NORMAL);
        page.addLine().addUnit("优惠金额:" + "\t" + order.getDiscountable_amount()+"元", FONT_NORMAL);

        page.addLine().addUnit("-------------------------------------------------------", FONT_NORMAL);

        page.addLine().addUnit("交易时间:" + "\t" + TimeUtils.stampToDate(order.getPaytime() + "000", TIME_FORMAT), FONT_NORMAL);
        page.addLine().addUnit("交易渠道:" + "\t" + order.getPay_name(), FONT_NORMAL);
        page.addLine().addUnit("交易描述:" + "\t" + order.getBody(), FONT_NORMAL);
        page.addLine().addUnit("终端编号:" + "\t" + SharedPreferencesUtils.getTerminalNumber(), FONT_NORMAL);
        page.addLine().addUnit("设备编号:" + "\t" + String.valueOf(tm.getDeviceId()), FONT_NORMAL);
        if(index==1){
            page.addLine().addUnit("凭证号:" + "\t" + String.valueOf(order.getTrade_no()), FONT_NORMAL);
        }
        page.addLine().addUnit("订单号", FONT_NORMAL, IImgProcessing.IPage.EAlign.LEFT,
                IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        page.addLine().addUnit(String.valueOf(order.getOut_trade_no()), FONT_NORMAL);

        //条形码
        page.addLine().addUnit(creatBarcode(mContext, String.valueOf(order.getOut_trade_no()), 520, 60), IImgProcessing.IPage.EAlign.CENTER);
//        page.addLine().adjustTopSpace(2);
//        page.addLine().addUnit("Scan to download Mpay", FONT_NORMAL, IImgProcessing.IPage.EAlign.CENTER);

        page.addLine().addUnit("备注:", FONT_NORMAL, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        page.addLine().addUnit("用户签名:", FONT_NORMAL, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);
        page.addLine().addUnit("\n\n\n\n", FONT_NORMAL);
        IImgProcessing imgProcessing = GetObj.getGL().getImgProcessing();
        return imgProcessing.pageToBitmap(page, 384);
    }

    public void print(String str, Boolean containBitmap) {
        //初始化
        PrinterTester.getInstance().init();
        //字体设置（ASCII，拓展码）
        PrinterTester.getInstance().fontSet(EFontTypeAscii.FONT_8_16, EFontTypeExtCode.FONT_16_16);
        //间距设置（字间距，行间距）
        PrinterTester.getInstance().spaceSet(Byte.parseByte("0"),
                Byte.parseByte("0"));

        //字符打印左边界
        PrinterTester.getInstance().leftIndents(Short.parseShort("0"));
        //打印黑度
        PrinterTester.getInstance().setGray(1);
        //双倍宽度<->正常宽度
        if (true) {
            PrinterTester.getInstance().setDoubleWidth(true, true);
        }
        //双倍高度<->正常高度
        if (true) {
            PrinterTester.getInstance().setDoubleHeight(true, true);
        }
        //正常打印<->反显打印
        PrinterTester.getInstance().setInvert(false);

        //打印图片
//        if (containBitmap) {
//            PrinterTester.getInstance().printBitmap(
////                    BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_qrcode));
//        }
        //打印状态
        String status = PrinterTester.getInstance().getStatus();

        //打印文本
        PrinterTester.getInstance().printStr(str, null);
        //走纸
        PrinterTester.getInstance().step(150);

        //开始打印
        PrinterTester.getInstance().start();
    }

    public void print(String orderNo, String orderTime, String orderAmt) {
        Bitmap bitmap = generate(orderNo, orderTime, orderAmt);
        //初始化
        PrinterTester.getInstance().init();
        String statues = PrinterTester.getInstance().getStatus();
        if (statues.contains("Success")) {
            PrinterTester.getInstance().printBitmap(bitmap);
            PrinterTester.getInstance().start();
        }
    }



    public Bitmap generate(String orderNo, String orderTime, String orderAmt) {
        IImgProcessing.IPage page = GetObj.getGL().getImgProcessing().createPage();
        //设置字体
//        page.setTypeFace(TYPE_FACE);
        //往页面里添加新的一行
//        page.addLine();
        //创建一个元素，可用IImgProcessing.IPage.ILine.addUnit(IUnit)来生成行
        page.adjustLineSpace(10);

        //logo
//        page.addLine().addUnit(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_mpay));

        // 凭单抬头
        page.addLine().addUnit("Payment Voucher", FONT_BIG, IImgProcessing.IPage.EAlign.CENTER, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);

        page.addLine().adjustTopSpace(20);

//        // 门店名称
//        page.addLine().addUnit("Store：" + MyApplication.getLoginResp().getUserBasicInfo().getMercName(),
//                FONT_NORMAL);
//
//        // 商户id
//        page.addLine().addUnit("Merchant ID：" + MyApplication.getLoginResp().getUserBasicInfo().getUserId(), FONT_NORMAL);
//
//        // 操作人员
//        page.addLine().addUnit("Operator：" + MyApplication.getLoginResp().getUserBasicInfo().getDisplayNm(), FONT_NORMAL);

        // Order：
        page.addLine().addUnit("Order：" + orderNo, FONT_NORMAL);

        // Payment_time：
        page.addLine().addUnit("Payment_time：" + orderTime, FONT_NORMAL);

        // Amount：
        page.addLine().addUnit("Amount：$" + orderAmt, FONT_NORMAL);

        // ===：
        page.addLine().addUnit("==================================", FONT_NORMAL, IImgProcessing.IPage.EAlign.CENTER);

        // Payment Successful：
        page.addLine().addUnit("Payment Successful", FONT_BIG, IImgProcessing.IPage.EAlign.CENTER, IImgProcessing.IPage.ILine.IUnit.TEXT_STYLE_BOLD);

        page.addLine().adjustTopSpace(20);

        // Print Time：
        page.addLine().addUnit("Print Time：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), FONT_NORMAL);

        // Terminal：
        page.addLine().addUnit("Terminal：" + SysTester.getInstance().getTerminfoModel() + " " + SysTester.getInstance().getDevInterfaceVer(), FONT_NORMAL);

        page.addLine().adjustTopSpace(20);

        //二维码
//        page.addLine().addUnit(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_qrcode), IImgProcessing.IPage.EAlign.CENTER);
//        page.addLine().adjustTopSpace(2);
//        page.addLine().addUnit("Scan to download Mpay", FONT_NORMAL, IImgProcessing.IPage.EAlign.CENTER);

        page.addLine().addUnit("\n\n\n\n\n\n", FONT_NORMAL);

        IImgProcessing imgProcessing = GetObj.getGL().getImgProcessing();
        return imgProcessing.pageToBitmap(page, 384);
    }

    public static Bitmap creatBarcode(Context context, String contents,
                                      int desiredWidth, int desiredHeight) {
        Bitmap resultBitmap = null;
        int marginW = 20;
        BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;

        resultBitmap = encodeAsBitmap(contents, barcodeFormat,
                desiredWidth, desiredHeight);

        return resultBitmap;
    }


    protected static Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int desiredWidth, int desiredHeight) {
        final int WHITE = 0xFFFFFFFF;
        final int BLACK = 0xFF000000;

        MultiFormatWriter writer = new MultiFormatWriter();
        BitMatrix result = null;
        try {
            result = writer.encode(contents, format, desiredWidth,
                    desiredHeight, null);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}
